package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * A utility class to hold generic util methods. All the methods are static.
 * 
 * @author singhgn
 * 
 */
public final class Utils {

	private Utils() {
		// This is private so that we don't accidently create multiple copies
	}

	/**
	 * This method is used to copy a file from a given source to destination
	 * 
	 * @param source
	 *            - The file that needs to be copied
	 * @param destination
	 *            - The file that needs to be created
	 * @return a boolean stating if the operation was successful or not
	 */
	public static boolean copy(File source, File destination) {
		int BUFFER_SIZE=1024*1024;//buffer size
		boolean result = false;

		if (source == null) {
			System.out.println("source cannot be null");
		}
		if (destination == null) {
			System.out.println("destination cannot be null");
		}
		try {
//			System.out.println(source);
//			System.out.println(destination);

			if (source.exists() && source.canRead()) {
				if (destination.createNewFile()) {
					System.out.println("copying " + source.getCanonicalPath()
							+ " to " + destination.getCanonicalPath());
					FileOutputStream fos = new FileOutputStream(destination);
					FileInputStream fis = new FileInputStream(source);
					byte[] buffer = new byte[BUFFER_SIZE];
					int bytes=0;
					int bytesWritten=0;
					try {
						while ((bytes=fis.read(buffer)) > -1) {
							fos.write(buffer,bytesWritten, bytes);
							bytesWritten+=bytes;
						}
					} finally {
						fos.close();
						fis.close();
					}
				} else {
					System.out.println("Cannot copy. File already exists at destination!");
					result = false;
				}

			} else {
				System.out
						.println("Cannot copy. Either source file doesn't exist or cannot be read!");
				result = false;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	private static void test1() {
		String source = "C:\\Office\\Project\\Automated\\ScheduledPricesReport\\Scheduled Prices For 20080724.xls";
//		String destination1 = "\\\\rlwhsqtcmfs1\\Grpareas2\\CLIENT VALUATIONS\\02 Client Valuations - Fixed Income\\99 Support\\02 Scheduled Prices\\Scheduled Prices For 20080724.xls";
		String destination2 = "C:\\Office\\Project\\Automated\\EODReport\\Scheduled Prices For 20080724.xls";
		String destination = destination2;
		copy(new File(source), new File(destination));
	}

	public static void main(String[] args) {
		test1();
	}
}
